from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializer import *
from rest_framework.response import Response
from goods.serializer import GoodSer
from goods.models import Good

# Create your views here.


class OrderInfoViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"

    # def retrieve(self, request, pk, *args, **kwarg):
    #     # 1. 查询当前订单对象
    #     order = self.get_object()
    #     order_ser = OrderInfoSer(order)
    #
    #     # 2.反向查询订单中的所有商品
    #     order_goods = order.orderGoods.all()
    #     order_goods_ser = OrderGoodsSer(order_goods, many=True)
    #
    #     # 3.修改订单商品的sku属性
    #     temp = []
    #     for i in order_goods_ser.data:
    #         i["sku"] = GoodSer(Good.objects.filter(i.get("sku")).first()).data
    #
    #         # 存入一个临时列表
    #         temp.append(i)
    #
    #     # 4. 修改订单 字典的skus 属性
    #
    #     order_dict = order_ser.data
    #     order_dict["skus"] = temp
    #
    #     return Response(order_dict)

    def retrieve(self, request, pk, *args, **kwargs):
        # 1. 检索当前的订单
        order = self.get_queryset().filter(order_id=pk).first()

        # 2. 序列化
        order_ser = self.get_serializer(order)

        # 3. 查询当前订单中的所有商品
        order_goods = order.orderGoods.all()
        order_goods_ser = OrderGoodsSer(order_goods, many=True)

        # 4. 获取每个商品的序列化信息
        order_goods_list = []
        for i in order_goods_ser.data:
            i["sku"] = GoodSer(Good.objects.filter(id=i.get("sku")).first()).data
            order_goods_list.append(i)

        # 5. 组织 json 数据
        my_data = order_ser.data
        my_data["skus"] = order_goods_list

        return Response(my_data)

    def update(self, request, *args, **kwargs):
        # 1.接受前端的数据
        status = request.data.get("status")

        # 2.获取要更新的对象
        order = self.get_object()

        # 更新状态
        order.status = status
        order.save()

        return Response({"code": 200, "msg": "更新订单状态成功"})
